package com.test.sdk.provider.service.impl;

import com.test.sdk.pojo.User;
import com.test.sdk.provider.dao.UserDAO;
import com.test.sdk.provider.exception.SdkException;
import com.test.sdk.provider.service.UserService;
import com.test.sdk.provider.util.AccountUtil;
import com.test.sdk.provider.util.DigestUtils;
import com.test.sdk.provider.util.ErrorConstants;
import com.test.sdk.provider.util.SdkConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDAO userDAO;

    @Autowired
    private RestTemplate restTemplate;//发http请求的

    @Autowired
    private RedisTemplate redisTemplate;//redis

    @Override
    public boolean doSendCode(String num) throws SdkException {
        Integer userId = userDAO.getUserIdByNum(num);
        if (userId != null) {//手机号已经被注册了
            throw new SdkException(ErrorConstants.MOBILE_EXIST);
        }
        if (redisTemplate.hasKey(num)) {//1分钟之内已经发过了
            return true;
        }
        String code = AccountUtil.getRandomCode(4);
        redisTemplate.opsForValue().set(num, code, 1, TimeUnit.MINUTES);
//        String url = "http://v.juhe.cn/sms/send?key=sadsadase3qw4rq3&tpl_id=119220&mobile=" + num + "&tpl_value=%23code%23%3D"+code;
//        Map<String, Object> result = restTemplate.getForObject(url, HashMap.class);
//        System.out.println(result);
        // return (int)result.get("error_code")==0;
        return true;
    }


    @Override
    public Integer doRegistByNum(String num, String code, String password) throws SdkException {
        Integer userId = userDAO.getUserIdByNum(num);
        if (userId != null) {//手机号已经被注册了
            throw new SdkException(ErrorConstants.MOBILE_EXIST);
        }
        String redisCode = (String) redisTemplate.opsForValue().get(num);
        System.out.println(redisCode+"="+code);
        if (redisCode == null || !redisCode.equals(code)) {//验证码过期，或没发过验证码  验证码错误
            throw new SdkException(ErrorConstants.CODE_ERROR);
        }
        redisTemplate.delete(num);
        User user = new User();
        user.setNum(num);
        user.setUserType(SdkConstants.USER_TYPE_FORMAL);
        user.setPassword(DigestUtils.getMD5(password + SdkConstants.PASSWORD_SALT));
        userDAO.addUser(user);
        userDAO.addUserNum(user);
        userDAO.addUserDynamic(user.getId());
        return user.getId();
    }
}
